package com.gree.common.exception;

import com.gree.common.entity.ReturnVo;
import com.gree.common.exception.base.BaseException;
import com.gree.common.exception.user.UserExpireException;
import com.gree.common.exception.user.UserLockedException;
import com.gree.common.exception.user.UserNoRoleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public ReturnVo baseException(BaseException e)
    {
        return new ReturnVo<>("500",e.getMessage());
    }

    @ExceptionHandler(UserExpireException.class)
    public ReturnVo handleAccountExpiredException(UserExpireException e)
    {
        log.error(e.getMessage(), e);
        return new ReturnVo<>("500",e.getMessage());
    }

    @ExceptionHandler(UserLockedException.class)
    public ReturnVo handleAccountExpiredException(UserLockedException e)
    {
        log.error(e.getMessage(), e);
        return new ReturnVo<>("500",e.getMessage());
    }

    @ExceptionHandler(UserNoRoleException.class)
    public ReturnVo handleAccountExpiredException(UserNoRoleException e)
    {
        log.error(e.getMessage(), e);
        return new ReturnVo<>("500",e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ReturnVo handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return new ReturnVo<>("500",e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return new ReturnVo<>("500",message);
    }

}
